﻿using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Objects.DataClasses;
using System.Linq;
using Com.JJ1369.Service.Model.Validator;

namespace Com.JJ1369.Service.Model
{
    // The MetadataTypeAttribute identifies DepartmentTypeMetadata as the class
    // that carries additional metadata for the DepartmentType class.
    [MetadataTypeAttribute(typeof(DepartmentType.DepartmentTypeMetadata))]
    public partial class DepartmentType:IValidatableObject
    {

        // This class allows you to attach custom attributes to properties
        // of the DepartmentType class.
        //
        // For example, the following marks the Xyz property as a
        // required property and specifies the format for valid values:
        //    [Required]
        //    [RegularExpression("[A-Z][A-Za-z0-9]*")]
        //    [StringLength(32)]
        //    public string Xyz { get; set; }
        internal sealed class DepartmentTypeMetadata
        {

            // Metadata classes are not meant to be instantiated.
            private DepartmentTypeMetadata()
            {
            }

            public EntityCollection<Department> DepartmentList { get; set; }

            [Key]
            public int DepartmentTypeID { get; set; }

            [Required(ErrorMessage="{0} 不能为空")]
            [CustomValidation(typeof(DepartmentTypeValidator), DepartmentTypeValidator.NamValidator)]
            [StringLength(8,ErrorMessage="{0}长度不能大于{1}.")]
            [Display(Name="名称")]
            public string Name { get; set; }
        }

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            BusinessWorkEntities entities = new BusinessWorkEntities();
            if (entities.DepartmentType.Any(d => d.Name == this.Name))
            {
                List<ValidationResult> result = new List<ValidationResult>();
                result.Add(new ValidationResult("名称已经存在.", new string[] { "Name" }));
                return result;
            }
            else
            {
                return new List<ValidationResult> { ValidationResult.Success };
            }
        }
    }
}
